import xarray as xr
import matplotlib.pyplot as plt
import seaborn as sns

# 安装依赖库的命令，可在终端运行
# pip install xarray netCDF4 matplotlib seaborn

def read_and_plot(): 
    file_path = 'E:\localfile\MYD021KM.A2017314.0345.061.2017314164621.hdf'
    var_name = 'Change_in_relative_responses_of_thermal_detectors'
    
    try:
        # 打开 HDF4 文件
        ds = xr.open_dataset(file_path, engine="netcdf4")
        
        # 读取变量数据
        if var_name in ds.variables:
            var_data = ds[var_name]
            
            # 处理高维数据，若数据维度大于 2，选择第一个切片
            while len(var_data.dims) > 2:
                first_dim = var_data.dims[0]
                var_data = var_data.isel({first_dim: 0})
            
            # 绘制热力图
            plt.figure(figsize=(10, 8))
            sns.heatmap(var_data, cmap='viridis')
            plt.title(f'{var_name} Heatmap')
            plt.xlabel(var_data.dims[1])
            plt.ylabel(var_data.dims[0])
            plt.show()
        else:
            print(f'错误：文件中未找到变量 {var_name}')
    except Exception as e:
        print(f'读取文件时出错: {str(e)}')

if __name__ == '__main__':
    read_and_plot()